<template>
  <div>
    <el-card class="box-card">
      <!--头部-->
      <template #header>
        <div class="card-header">
          <div class="cardsize">
            <h2 style="font-size: 18px; font-weight: bold">志愿填报</h2>
            <div style="font-size: 15px">共 {{ pageData.total ?? 0 }} 单</div>
            <div style="font-size: 15px">
              已处理 {{ totalCount.orderStatus_1 }} 单
            </div>
            <div style="font-size: 15px">
              已审核 {{ totalCount.orderStatus_2 }} 单
            </div>
            <div style="font-size: 15px">
              已完成 {{ totalCount.orderStatus_3 }} 单
            </div>
          </div>
        </div>
      </template>
      <!--列表数据-->
      <el-row :gutter="20">
        <el-col :span="5">
          <el-input
            v-model="pageData.search"
            placeholder="考生/考生/手机号"
            clearable
            @clear="searchChange"
          >
            <template #append>
              <el-button
                type="primary"
                style="height: 40px"
                @click="searchChange"
                >搜索</el-button
              >
            </template>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="pageData.gkaProvinceNumId"
            class="m-2"
            placeholder="省份"
            size="large"
            clearable
            @change="searchChange"
          >
            <el-option
              v-for="item in provincelist"
              :key="item.id"
              :label="item.provinceName"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="pageData.graduate_time"
            class="m-2"
            placeholder="高考年份"
            size="large"
            clearable
            @change="searchChange"
          >
            <el-option
              v-for="item in gaokaoyear"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="pageData.orderStatus"
            class="m-2"
            placeholder="状态"
            size="large"
            clearable
            @change="searchChange"
          >
            <el-option
              v-for="item in statuslist"
              :key="item.val"
              :label="item.name"
              :value="item.val"
            />
          </el-select>
        </el-col>
        <el-col :span="10" style="display: flex; justify-content: flex-end">
          <el-button
            style="height: 40px"
            @click="onClickBatchDistribution"
            v-hasPermi="['leader:filling:add']"
            >批量分配</el-button
          >
          <el-button
            :icon="Bottom"
            style="height: 40px"
            @click="onClickOrdersExport"
            v-hasPermi="['leader:filling:download']"
            >下载</el-button
          >
          <el-button
            type="primary"
            :icon="Plus"
            style="height: 40px"
            @click="addUserOrder"
            v-hasPermi="['leader:filling:addkd']"
            >创建客单</el-button
          >
        </el-col>
      </el-row>
      <el-divider />
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        v-loading="isRequest"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          type="selection"
          width="30"
          :selectable="isRowSelectable"
        />
        <el-table-column
          prop="gkaProvinceName"
          label="省份"
          align="center"
          width="70"
        >
        </el-table-column>
        <el-table-column prop="studentName" label="姓名" align="center">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.gkaProvinceName"
              placement="top"
            >
              <div
                v-if="!scope.row.student"
                style="color: #165dff; cursor: pointer"
                :class="{
                  isPassed: scope.row.passed,
                }"
              >
                {{ scope.row.studentName }}
              </div>
              <div
                v-else
                style="color: #165dff; cursor: pointer"
                :class="{
                  isPassed: scope.row.passed,
                }"
                @click="lookUserInfo(scope.row)"
              >
                {{ scope.row.studentName }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="student.sex"
          label="性别"
          align="center"
          width="50"
        >
          <template #default="scope">
            <div>{{ (scope.row.student || {}).sex == 0 ? '男' : '女' }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="studentMobile"
          label="手机号"
          width="110"
          align="center"
        />
        <el-table-column
          prop="student.graduate_time"
          label="高考年份"
          width="80"
          align="center"
        />
        <el-table-column prop="grade" label="成绩" width="220" align="center">
          <template #default="scope">
            <div v-if="!!scope.row.student">
              <div
                v-if="
                  scope.row.isGKB == 1 && scope.row.student.gkb_score_num == 0
                "
                @click="lookGradeChange(scope.row)"
                style="color: rgb(22, 93, 255)"
              >
                请创建高考成绩
              </div>
              <div
                v-else-if="
                  scope.row.isGKB == 1 && scope.row.student.gkb_score_num == 1
                "
              >
                {{
                  scope.row.student
                    ? scope.row.student.score +
                      '分 ' +
                      scope.row.student.section +
                      '位 ' +
                      scope.row.student.sgname
                    : ''
                }}
              </div>
              <div v-else>
                {{
                  scope.row.student
                    ? scope.row.student.score +
                      '分 ' +
                      scope.row.student.section +
                      '位 ' +
                      scope.row.student.sgname
                    : ''
                }}
                <el-icon
                  size="18"
                  @click="lookGradeChange(scope.row)"
                  style="cursor: pointer"
                >
                  <EditPen />
                </el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="teacher" label="老师" width="130" align="center">
          <template #default="scope">
            <div
              v-if="!scope.row.student"
              :class="scope.row.passed == 1 ? 'isPassed' : ''"
            >
              {{ scope.row.teacher }}
            </div>
            <div v-else>
              <el-dropdown trigger="click" :disabled="scope.row.passed == 1">
                <span
                  :class="
                    scope.row.passed == 1 ? 'isPassed' : 'el-dropdown-link'
                  "
                >
                  {{ scope.row.teacher }}
                  <el-icon
                    class="el-icon--right"
                    v-hasPermi="['leader:filling:add']"
                  >
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu
                    v-hasPermi="['leader:filling:add']"
                    style="
                      max-height: 400px;
                      overflow: hidden;
                      overflow-y: auto;
                      padding: 10px;
                    "
                  >
                    <el-select-v2
                      filterable
                      model-value=""
                      :options="teacherArr"
                      :props="{
                        label: 'realName',
                        value: 'id',
                      }"
                      value-key="id"
                      placeholder="请选择老师"
                      style="width: 240px"
                      @change="
                        (selectedValue) => onChangeFilter(scope, selectedValue)
                      "
                    />
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="creationTime"
          label="创建时间"
          width="160"
          align="center"
        >
          <template #default="scope">
            <div>{{ scope.row.creationTime }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <div>{{ scope.row.orderStatus == 1 ? '已处理' : '未处理' }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="zyTableCount"
          label="报告"
          fixed="right"
          align="center"
        >
          <template #default="scope">
            <div @click="handleEva(scope.row)" class="eva">
              {{ scope.row.evaluationCount }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="table"
          label="志愿表"
          fixed="right"
          width="120"
          align="center"
        >
          <template #default="scope">
            <div
              v-if="!!scope.row.student"
              class="zyb-count"
              :class="scope.row.passed == 1 ? 'zyb-count-isPassed' : ''"
              style="cursor: pointer"
              @click="onClickzybList(scope.row)"
            >
              <div>模{{ scope.row.zyTableCommonCount }}</div>
              <div>高{{ scope.row.zyTableGKCount }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="填报" width="50">
          <template #default="scope">
            <div
              style="
                display: flex;
                justify-content: center;
                align-items: center;
              "
              v-if="!!scope.row.student && scope.row.passed == 0"
            >
              <el-tooltip
                v-if="
                  scope.row.isGKB == 1 && scope.row.student.gkb_score_nufm == 0
                "
                class="box-item"
                effect="dark"
                content="请先创建高考成绩"
                placement="top"
              >
                <el-icon
                  size="24"
                  color="#165dff"
                  style="cursor: pointer; color: #86909c"
                >
                  <Edit />
                </el-icon>
              </el-tooltip>

              <el-tooltip
                v-else-if="scope.row.student.score !== 0"
                class="box-item"
                effect="dark"
                content="填报"
                placement="top"
              >
                <el-icon
                  size="24"
                  :color="'#165dff'"
                  style="cursor: pointer"
                  @click="fillSubmitChange(scope.row)"
                  v-hasPermi="['leader:filling:filling']"
                >
                  <Edit />
                </el-icon>
              </el-tooltip>
              <!-- 单招填报按钮 -->

              <p
                v-if="false"
                @click="fillSubmitChange(scope.row, '单招')"
                style="color: #165dff; padding-left: 10px; cursor: pointer"
              >
                单招填报
              </p>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 20px"
        :current-page="pageData.page"
        :page-size="pageData.pageSize"
        v-if="pageData.total"
        :page-sizes="[10, 20, 30, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 批量分配 -->
    <batchDistribution
      ref="batchDistributionRef"
      :teacherArr="teacherArr"
      :selStudentArr="selStudentArr"
      @refreshList="pagination"
    >
    </batchDistribution>
    <!-- 添加用户 -->
    <addUserInfo
      ref="addUserInfoRef"
      :provincelist="gkaProvinceNumIdForAddUser"
      :gaokaoyear="studentGaoKaoYearAddUser"
      @refreshStudentList="pagination"
      @getTzyCount="getTzyCount"
    ></addUserInfo>
    <!--查看用户详情-->
    <lookuserDate ref="lookuserDateRef"></lookuserDate>
    <!--用户修改信息-->
    <userUpdate
      ref="userUpdatesRef"
      @refreshStudentList="pagination"
      @getTzyCount="getTzyCount"
    ></userUpdate>
    <!--志愿表数据-->
    <userZyList ref="userZyListsRef" :row="row"> </userZyList>
    <!--填报-->
    <filingDialog
      ref="filingDialogsRef"
      @openSetScore="openSetScore"
    ></filingDialog>
    <report ref="reportRef" :studentData="studentData" />
  </div>
</template>

<script setup>
import report from './module/report.vue';
// import { getIsGKB } from "@/api/appv2/appv1";
import addUserInfo from './module/addUserInfo.vue';
import lookuserDate from './module/lookuserDate.vue';
import { Plus, Bottom } from '@element-plus/icons-vue';
import userUpdate from './module/userUpdate.vue';
import userZyList from './module/userZyList.vue';
import filingDialog from './module/filingDialog.vue';
import batchDistribution from './module/batchDistribution.vue';
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { omit } from 'lodash';
import {
  tzyOrders,
  getProvince,
  tzyOrdersCount,
  tzyOrdersCreate,
  tzyOrdersListFilter,
  tzyOrdersExport,
} from '@/api/leader/Filling.js';
import { getProvinceList } from '@/api/appv2/appv2';
import bus from '@/utils/bus.js';
import { accountListExpserts } from '@/api/system/account.js';
import { ElMessage } from 'element-plus';
const route = useRoute();
const row = ref()
const reportRef = ref(null);
const batchDistributionRef = ref(null);
const addUserInfoRef = ref(null);
const lookuserDateRef = ref();
const userUpdatesRef = ref(null);
const userZyListsRef = ref(null);
const filingDialogsRef = ref(null);
const groupId = ref()
const tableData = ref([]);
const pageData = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  search: '',
});
const provinceList = ref([]);
const totalCount = ref({});
const provincelist = ref([]); // 省份
const gaokaoyear = ref([]); // 高考年份
const gkaProvinceNumIdForAddUser = ref([]); // 创建所需高考省份
const studentGaoKaoYearAddUser = ref([]); // 创建所需高考年份
const statuslist = ref([]); // 查询状态
const isRequest = ref(false);
const teacherArr = ref([]); // 老师数组
const selStudentArr = ref([]); // 选中学生数组
const isGkData = ref({});
const studentData = ref({});
const handleEva = (data) => {
  localStorage.setItem('student_id', data.studentId);
  studentData.value = data.student;
  if (data.evaluationCount > 0) {
    reportRef.value.handleOpenReport(data);
  } else {
    return;
  }
};
bus.on('refreshList', () => {
  pageData.value.page = 1;
  pagination();
});
// 切换大小
const handleSizeChange = (val) => {
  pageData.value.pageSize = val;
  pagination();
};
// 切换页码
const handleCurrentChange = (val) => {
  pageData.value.page = val;
  pagination();
};
// const fetchIsGKB = () => {
//   getIsGKB().then((res) => {
//     isGkData.value = res.data;
//     if (isGkData.value.isGKB == "1") {
//       ElMessage({
//         message: "当前为高考版",
//         type: "warning",
//       });
//     }
//   });
// };
// fetchIsGKB();
const fetchProvince = () => {
  getProvinceList().then((res) => {
    provincelist.value = res.data;
  });
};
fetchProvince();
function searchDate() {
  tzyOrdersListFilter().then((res) => {
    // provincelist.value = res.data[0].data;
    gaokaoyear.value = res.data[1].data;
    statuslist.value = res.data[2].data;
    gkaProvinceNumIdForAddUser.value = res.data[3].data;
    studentGaoKaoYearAddUser.value = res.data[4].data;
  });
}
searchDate();

function getTzyCount() {
  tzyOrdersCount().then((res) => {
    totalCount.value = res.data;
  });
}
getTzyCount();

function searchChange() {
  // 添加查询参数
  pageData.value.page = 1;
  pagination();
}

function pagination() {
  // pageData.value.page = page
  // 分页加载请求数据
  if (isRequest.value) return;
  isRequest.value = true;

  let data = pageData.value;
  Object.keys(data).forEach((key) => {
    // 检查值是否为数组、字符串并且长度为0，或值为 undefined
    if (
      (Array.isArray(data[key]) && data[key].length === 0) ||
      data[key] === undefined ||
      data[key] === null
    ) {
      delete data[key];
    }
  });
  tzyOrders(omit(data, 'total'))
    .then((res) => {
      isRequest.value = false;

      tableData.value = res.data.data;

      pageData.value.page = res.data.current_page;
      pageData.value.total = res.data.total;
    })
    .catch(() => {
      isRequest.value = false;
    });
}
pagination();

// 检测每一行是否能被选中
const isRowSelectable = (row) => {
  // 可以根据行的某些条件判断是否禁用
  return row.passed != 1;
};

// 置灰
const tableRowClassName = ({ row }) => {
  if (row.passed === 1) {
    return 'ashes';
  }
  return '';
};
getAccountList();
// 获取老师列表
function getAccountList() {
  accountListExpserts({
    pageSize: 999,
  }).then((res) => {
    teacherArr.value = res.data.data;
  });
}

// 学生勾选数据改变
function handleSelectionChange(val) {
  selStudentArr.value = val;
}

const onChangeFilter = (scope, teacherId) => {
  let index = scope.$index;
  const teacher = teacherArr.value.find(
    (item) => item.id === teacherId
  )?.realName;
  let data = { id: scope.row.id, teacherId, teacher };

  // 更新用户信息
  tzyOrdersCreate(data).then(() => {
    tableData.value[index].teacherId = teacherId;
    tableData.value[index].teacher = teacher;
    // 更新表单数量
    getTzyCount();
  });
};

// function onClickAccounList(command) {
//   let item = command.item;
//   let index = command.index;

//   let data = {};
//   data['id'] = tableData.value[index].id;
//   data['teacherId'] = item.id;
//   data['teacher'] = item.realName;

//   // 更新用户信息
//   tzyOrdersCreate(data).then(() => {
//     tableData.value[index].teacherId = item.id;
//     tableData.value[index].teacher = item.realName;
//     // 更新表单数量
//     getTzyCount();
//   });
// }

// 批量分配
function onClickBatchDistribution() {
  if (selStudentArr.value.length == 0) {
    ElMessage({
      message: '请选择需要分配的学生',
      type: 'warning',
    });
    return;
  }
  batchDistributionRef.value.openChange();
}

// 导出客单列表
function onClickOrdersExport() {
  tzyOrdersExport(pageData.value).then((res) => {
    window.location.href = res.data.url;
    ElMessage.success('导出成功');
  });
}

// 创建用户
function addUserOrder() {
  addUserInfoRef.value.showAddUserInfo();
}

// 用户详情
function lookUserInfo(val) {
  if (val.passed) return;
  lookuserDateRef.value.openChange(val);
}

// 点击查看志愿列表
function onClickzybList(val) {
  localStorage.setItem('student_id', val.studentId);
  localStorage.setItem('student_Province', val.gkaProvinceNumId);
  userZyListsRef.value.openChange(val);
  row.value = val
}

function lookGradeChange(val) {
  if (val.passed) return;
  userUpdatesRef.value.openChange(val);
}

const provinceDataList = async () => {
  getProvince().then((res) => {
    provinceList.value = res.data;
    localStorage.setItem(
      'provinceDataList',
      JSON.stringify(provinceList.value)
    );
  });
};
provinceDataList();

let gkType = ref(null); // 弹出表格是否隐藏相关数据
function fillSubmitChange(val, text) {
  val.isDzTypeDiff =
    provinceList.value.filter((item) => item.id == val.gkaProvinceNumId)[0]
      ?.isDzTypeDiff || 0;
  localStorage.removeItem('courseNew');

  if (text == '单招' && !['四川'].includes(val.gkaProvinceName)) {
    ElMessage({
      message: '单招目前仅限四川地区',
      type: 'warning',
    });
    return;
  }
  gkType.value = text; //判断弹出表格是否隐藏相关数据
  localStorage.setItem('student_id', val.studentId);
  localStorage.setItem('student_Province', val.gkaProvinceNumId);
  filingDialogsRef.value.openChange(val, isGkData.value, gkType.value);
}

const openSetScore = (val) => {
  const studentInfo = tableData.value.filter((item) => item.id == val.id)[0];
  userUpdatesRef.value.openChange(studentInfo, val.formType);
};
onMounted(() => {
  if (route.query.dialog == 'true') {
    addUserInfoRef.value.showAddUserInfo();
  }
  const parsedUserDateInfo = localStorage.getItem('userDateInfo') ? JSON.parse(localStorage.getItem('userDateInfo')) : {};
  groupId.value = parsedUserDateInfo.groupId;
  // console.log(groupId.value,"groupId.valuegroupId.value");
  
});
</script>
<style lang="scss" scoped>
@import '@/assets/styles/global.scss';
:deep(.el-dialog) {
  max-height: none !important;
}
.eva {
  cursor: pointer;
}

.zyb-count {
  background: #fff;
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid #165dff;
  padding: 5px 10px;
  font-size: 14px;
  font-family:
    PingFang SC-Regular,
    PingFang SC;
  font-weight: 400;
  line-height: 14px;
  display: flex;
  justify-content: space-between;
  color: #165dff;
}
.zyb-count-isPassed {
  border: 1px solid #cdcdcd;
  color: #cdcdcd;
}

.box-card {
  margin: 20px;
  .cardsize {
    display: flex;
    align-items: center;
    font-weight: 400;

    div {
      margin-left: 20px;
    }
  }
}
:deep(.el-table .ashes) {
  color: #cdcdcd !important;
}
.isPassed {
  color: #cdcdcd !important;
}
</style>
